<template>
  <el-row :gutter="20">
    <el-col :span="6">
      <el-card>
        <el-form
          :rules="rules"
          :inline="true"
          ref="conncectFormRef"
          :model="connectForm"
          class="form-contain"
          size="small"
        >
          <el-form-item :label="t('websocket.protocol')" prop="protocol">
            <el-input
              v-model="connectForm.protocol"
              :disabled="websocketClientStatus"
              :placeholder="t('websocket.protocol')"
            />
          </el-form-item>
          <el-form-item :label="t('websocket.ip')" prop="ip">
            <el-input
              v-model="connectForm.ip"
              :disabled="websocketClientStatus"
              :placeholder="t('websocket.ip')"
            />
          </el-form-item>
          <el-form-item :label="t('websocket.port')" prop="port">
            <el-input
              type="number"
              v-model.number="connectForm.port"
              :disabled="websocketClientStatus"
              :placeholder="t('websocket.port')"
            />
          </el-form-item>

          <el-form-item :label="t('websocket.path')" prop="path">
            <el-input
              v-model.number="connectForm.path"
              :disabled="websocketClientStatus"
              placeholder="路由路径(必须以/开头)"
              @keuyp.enter="connect(conncectFormRef)"
            />
          </el-form-item>

          <el-form-item>
            <el-button
              :type="websocketClientStatus ? 'danger' : 'primary'"
              @click="connect(conncectFormRef)"
              :loading="loading"
            >
              {{
                t(
                  websocketClientStatus
                    ? 'websocket.disconnect'
                    : 'websocket.connect'
                )
              }}
            </el-button>
          </el-form-item>
        </el-form>

        <el-form
          ref="ruleFormRef"
          :model="websocketForm"
          :rules="rules"
          class="demo-ruleForm"
          label-position="top"
          size="small"
        >
          <el-form-item :label="t('websocket.message')" prop="message">
            <el-input
              type="textarea"
              :rows="18"
              :placeholder="t('websocket.message')"
              v-model="websocketForm.message"
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="submitForm(ruleFormRef)"
              :disabled="!websocketClientStatus"
              :loading="loading"
            >
              {{ t('websocket.send') }}
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">
              {{ t('websocket.reset') }}
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-col>
    <el-col :span="18">
      <Log />
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import {
  ElMessage,
  FormInstance,
  FormRules,
  TabsPaneContext,
} from 'element-plus'
import {
  onBeforeUnmount,
  onBeforeUpdate,
  onMounted,
  onUnmounted,
  reactive,
  ref,
} from 'vue'
import Log from '@/components/Log/websocketLog.vue'
import { closeClient, creatClient, sendMessageByClient } from '@/api/websocket'
import { useI18n } from 'vue-i18n'
import { websocketStore } from '@/store/websocketStore'
import { storeToRefs } from 'pinia'
import { WebsocketMessage } from '@/types/websocket'
import dayjs from 'dayjs'

const { t } = useI18n()

const loading = ref(false)
const websocketstore = websocketStore()

const store = websocketStore()
const ruleFormRef = ref<FormInstance>()

const websocketForm: WebsocketMessage = reactive({
  message: '',
})

// initWebSocket('simulator')
const {
  websocketClientStatus,
  websocketClientIp,
  websocketClientPort,
  websocketClientPath,
} = storeToRefs(store) // 连接状态

// 连接信息表单
const connectForm = reactive({
  protocol: 'ws',
  ip: websocketClientIp.value,
  port: websocketClientPort.value,
  path: websocketClientPath.value,
})

// 表单校验规则
const rules = reactive<FormRules>({
  protocol: [{ required: true, message: '请填写通信协议', trigger: 'blur' }],
  ip: [{ required: true, message: '请填写IP地址', trigger: 'blur' }],
  port: [
    {
      required: true,
      message: '请填写连接端口',
      trigger: 'change',
    },
    { type: 'number', message: '端口号必须为数字类型' },
  ],
  path: [
    {
      required: true,
      message: '请填写连接路由',
      trigger: 'change',
    },
  ],
  message: [
    {
      required: true,
      message: '请填写报文',
      trigger: 'change',
    },
  ],
})

const { ws } = storeToRefs(store)

// 创建客户端
const conncectFormRef = ref<FormInstance>()
const connect = async (formEl: FormInstance | undefined) => {
  // 储存ip和port，解决刷新丢失
  store.setWebsocketClientIp(connectForm.ip)
  store.setWebsocketClientPort(connectForm.port)

  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (websocketClientStatus.value) {
        // 端开连接
        ws.value.close()
        websocketstore.setWebsocketClientStatus(false)
      } else {
        creatWebsocket()
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 发送消息
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      ws.value.send(websocketForm.message)
      websocketstore.setWebsocketLog(
        dayjs().format('YYYY-MM-DD HH:mm:ss') +
          ' client send:' +
          websocketForm.message
      )
    } else {
      console.log('error submit!', fields)
    }
  })
}

onBeforeUpdate(() => {
  ws.value.close()
})

// 重置消息表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

/**
 * 建立连接
 */
const creatWebsocket = () => {
  ws.value = new WebSocket(
    connectForm.protocol +
      '://' +
      connectForm.ip +
      ':' +
      connectForm.port +
      connectForm.path
  )
  ws.value.onerror = (env: Event) => {
    ElMessage({
      showClose: true,
      message: '连接失败',
      type: 'error',
      duration: 1000,
    })
    websocketstore.setWebsocketLog(
      dayjs().format('YYYY-MM-DD HH:mm:ss') + ' Websocket client is closed!'
    )
    websocketstore.setWebsocketClientStatus(false)
  }
  ws.value.onopen = (env: Event) => {
    ElMessage({
      showClose: true,
      message: '连接成功',
      type: 'success',
      duration: 1000,
    })
    websocketstore.setWebsocketLog(
      dayjs().format('YYYY-MM-DD HH:mm:ss') + ' Websocket client is opened!'
    )
    websocketstore.setWebsocketClientStatus(true)
  }
  ws.value.onmessage = (env: MessageEvent) => {
    console.log('收到消息')

    websocketstore.setWebsocketLog(
      dayjs().format('YYYY-MM-DD HH:mm:ss') + ' client get:' + env.data
    )
  }
  ws.value.onclose = (env: Event) => {
    websocketstore.setWebsocketLog(
      dayjs().format('YYYY-MM-DD HH:mm:ss') + ' Websocket client is close!'
    )
    // console.log('尝试重连...')
    // creatWebsocket()
    websocketstore.setWebsocketClientStatus(false)
  }
}
</script>
<style scoped lang="scss">
.form-contain {
  margin-bottom: 20px;
}
</style>
